#!/usr/bin/perl 
#             -w  affiche warning 
##########################################################################################################################
##########################################################################################################################
my $sources = $ARGV[0] ; 
my $path = $ARGV[1] ;
my $numbcluster = 0;
my $numbevents = 0;
my $idcluster=0;
my $numinfo = 10;

`mv clusters.m clusters.old.m`;
open (OUT,">".$path."clusters.m");

my @list = `ls -dl $sources/????/??/??/???????????????? | grep drwxr` ;
$numbcluster =  $#list + 1;
print OUT "function [clust]=clusters\n\n\n% function generated by NNK_dendro_1.pl\n% usage : [clust]=clusters ;\n" ;
print OUT "% fields of cell 'clust' : clust{i} clusters id i\n";
print OUT "%                          clust{i}(k,:) event k all informations\n";
print OUT "%                          clust{i}(k,1) path of event k (char)\n";
print OUT "%                          clust{i}(k,2) name of event k (char, 'yyyymmddHHMMSSXX')\n";  
print OUT "%                          clust{i}(k,3) date of event k (num, matlab day)\n";
print OUT "\nclust=cell($numbcluster,1);\n";
foreach $item(@list) {
	chomp($item) ;
	$idcluster = $idcluster + 1;
	my @elt = split(' ', $item) ;
	my $paf = $elt[-1] ; 
	my @intralist = `ls -d $paf/events/*` ;
	my $numbevent =  $#intralist + 1;
	my $idevent = 0; 
	print OUT "clust{$idcluster}=cell($numbevent,$numinfo);\n";
	foreach $event(@intralist) {
		chomp($event) ;
		$idevent = $idevent + 1;
		print OUT "clust{$idcluster}{$idevent,1} = '$event' ; \n" ;

		my @eltevent = split("/",$event);
		my $date = substr($eltevent[-1],0,14) ;
		print OUT "clust{$idcluster}{$idevent,2} = '$eltevent[-1]' ; \n" ;
		print OUT "clust{$idcluster}{$idevent,3} = datenum('$date','yyyymmddHHMMSS') ; \n" ;
	}
}

close(OUT) ; 
